package com.zf.yichat.controller.ticket;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.google.zxing.WriterException;
import com.zf.yichat.config.utils.GoogleAuthenticationToolUtils;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.dto.StGoodsDto;
import com.zf.yichat.dto.StTicketDto;
import com.zf.yichat.mapper.StOfficialTicketMapper;
import com.zf.yichat.mapper.StUserTicketMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.TicketsService;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 门票管理
 */
@Controller
@RequestMapping("ticket")
@Slf4j
public class StTicketController extends BaseController {


    @Resource
    private StOfficialTicketMapper officialTicketMapper;

    @Autowired
    private TicketsService ticketsService;

    @Resource
    private StUserTicketMapper userTicketMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 门票列表
     * @return
     */
    @RequestMapping("/page/list")
    public String index() {
        return "ticket/list";
    }

    /**
     * 新增门票
     * @return
     */
    @RequestMapping("/page/add")
    public String add() {
        return "ticket/add";
    }

    /**
     * 编辑门票
     * @return
     */
    @RequestMapping("/page/edit")
    public String edit(Integer id) {

        StOfficialTicket ticket = officialTicketMapper.selectByPrimaryKey(id);
        StTicketDto stTicketDto = new StTicketDto();
        BeanUtils.copyProperties(ticket, stTicketDto);
        Date startDate = stTicketDto.getStartDate();
        stTicketDto.setStartTime(DateUtil.format(startDate, "yyyy-MM-dd"));

        getRequest().setAttribute("ticket", stTicketDto);
        return "ticket/edit";
    }
    /**
     * 门票扫描记录
     * @return
     */
    @RequestMapping("/page/record")
    public String record(String ticketCode) {
        getRequest().setAttribute("ticketCode", ticketCode);
        return "ticket/record";
    }

    /**
     * 门票列表
     * @param page
     * @param limit
     * @param status
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public FsResponse goodsList(Integer page, Integer limit, Integer status) {
        Example example = new Example(StOfficialTicket.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != status) {
            criteria.andEqualTo("status", status);
        }

        PageHelper.startPage(page, limit);
        return DtoChangeUtils.getPageList(officialTicketMapper.selectByExample(example), data -> {
            StTicketDto ticket = new StTicketDto();
            BeanUtils.copyProperties(data, ticket);

            // 查询已赠送次数
            Example userExample = new Example(StUserTicket.class);
            userExample.createCriteria().andEqualTo("ticketCode", data.getTicketCode()).andEqualTo("ticketType", StUserTicket.TYPE_OFFICIAL);
            Integer scannedCount  = userTicketMapper.selectCountByExample(userExample);
            ticket.setScannedCount(scannedCount);
            Date startDate = ticket.getStartDate();
            ticket.setStartTime(DateUtil.format(startDate, "yyyy-MM-dd"));
            return ticket;
        });
    }


    /**
     * 新增门票
     * @param ticketDto
     * @return
     */
    @RequestMapping("/addTicket")
    @ResponseBody
    public FsResponse addTicket(StTicketDto ticketDto) throws Exception {

        String startTime = ticketDto.getStartTime();
        if (StringUtils.isNotBlank(startTime)) {
            Date startDate = DateUtil.parse(startTime);
            ticketDto.setStartDate(startDate);
        }

        // 生成二维码图片
        String ticketCode = IdUtil.simpleUUID();
        String purposeType = StTicketDto.PURPOSE_TYPE_GIVE;
        StTicketDto jsonTick = new StTicketDto();
        jsonTick.setTicketCode(ticketCode);
        jsonTick.setPurposeType(purposeType);
        String qrCodeAddress = GoogleAuthenticationToolUtils.createQRCode(JSON.toJSONString(jsonTick),null,512,512);

        StOfficialTicket ticket = new StOfficialTicket();
        BeanUtils.copyProperties(ticketDto, ticket);
        ticket.setTicketCode(ticketCode);
        ticket.setCreateTime(new Date());
        ticket.setQrCodeAddress(qrCodeAddress);
        officialTicketMapper.insertSelective(ticket);
        return FsResponseGen.successMsg("添加成功！");
    }


    /**
     *  编辑门票
     * @param ticketDto
     * @return
     */
    @RequestMapping("/editTicket")
    @ResponseBody
    public FsResponse editTicket(StTicketDto ticketDto) {

        String startTime = ticketDto.getStartTime();
        if (StringUtils.isNotBlank(startTime)) {
            Date startDate = DateUtil.parse(startTime);
            ticketDto.setStartDate(startDate);
        }

        StOfficialTicket ticket = new StOfficialTicket();
        BeanUtils.copyProperties(ticketDto, ticket);
        officialTicketMapper.updateByPrimaryKeySelective(ticket);
        return FsResponseGen.successMsg("编辑成功！");
    }

    /**
     *  删除门票
     * @param ticketId
     * @return
     */
    @RequestMapping("/delTicket")
    @ResponseBody
    public FsResponse delTicket(Integer ticketId) {
        officialTicketMapper.deleteByPrimaryKey(ticketId);
        return FsResponseGen.successMsg("删除成功！");
    }

    /**
     *  查询门票扫码记录
     * @param ticketCode
     * @return
     */
    @RequestMapping("/queryUserScanCode")
    @ResponseBody
    public FsResponse queryUserScanCode(Integer page, Integer limit, Integer status, Long userId, String ticketCode) {
        Example example = new Example(StUserTicket.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != userId) {
            criteria.andEqualTo("userId", userId);
        }

        if (null != status) {
            criteria.andEqualTo("status", status);
        }

        criteria.andEqualTo("ticketCode", ticketCode).andEqualTo("ticketType", StUserTicket.TYPE_OFFICIAL);
        PageHelper.startPage(page, limit);

        return DtoChangeUtils.getPageList(userTicketMapper.selectByExample(example), ticket -> {
            StTicketDto stTicketDto = new StTicketDto();
            stTicketDto.setStatus(ticket.getStatus());
            stTicketDto.setCreateTime(ticket.getCreateTime());
            User user = userMapper.queryUserByParam("", ticket.getUserId());
            if (null != user) {
                stTicketDto.setUserId(user.getId());
                stTicketDto.setNick(user.getNick());
                stTicketDto.setAvatar(user.getAvatar());
            }
            return stTicketDto;
        });
    }
}
